package com.example.huawei.system.controller;

import com.example.huawei.system.result.Result;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@Api(tags = "图片上传")
@RestController
@RequestMapping("/common")
@Slf4j
public class FileController {
    /**
     * 时间格式化
     */
    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd/");

    /**
     * 图片保存路径，自动从yml文件中获取数据
     * 示例： E:/images/
     */
    @Value("${file-save-path}")
    private String fileSavePath;

    @PostMapping(path = "/upload")
    public Result<?> uploadFile(@RequestParam("file") MultipartFile[] file, HttpServletRequest request) {
        if (file.length <= 0) {
            return Result.error().message("文件不能为空");
        }
        //1.后半段目录
        String directory = simpleDateFormat.format(new Date());
        /*
         *  2.文件保存目录  E:/images/2020/03/15/
         *  如果目录不存在，则创建
         */
        File dir = new File(fileSavePath + directory);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        log.info("图片上传，保存位置：" + fileSavePath + directory);
        List<String> list = new ArrayList<>();

        StringBuilder url = new StringBuilder();
        int i = 0;
        for (MultipartFile multipartFile : file) {
            //3.给文件重新设置一个名字
            //后缀
            String suffix = Objects.requireNonNull(multipartFile.getOriginalFilename()).substring(multipartFile.getOriginalFilename().lastIndexOf("."));
            String newFileName = UUID.randomUUID().toString().replaceAll("-", "") + suffix;
            //4.创建这个新文件
            File newFile = new File(fileSavePath + directory + newFileName);
            //5.复制操作
            try {
                multipartFile.transferTo(newFile);
                //协议 :// ip地址 ：端口号 / 文件目录(/images/2020/03/15/xxx.jpg)
                if (i == 0) {
                    url = new StringBuilder("/images/" + directory + newFileName);
                } else {
                    url.append(",/images/").append(directory).append(newFileName);
                }
                i++;
                log.info("图片上传，访问URL：" + url);

            } catch (IOException e) {
                return Result.error();
            }
        }
        return Result.ok(url.toString());
    }

}
